const WebSocket = require('ws');
const http = require('http');

const options = {};
const httpServer = http.createServer(options, (req, res) => {
    const contentType = "text/html";
    response.writeHead(200, {
        'Content-Type': contentType
    });
    response.write("Not Found", "utf-8");
    response.end();
});

httpServer.listen(8081, () => {
    console.log(`WebSocket server is running on ws://localhost:8081`);
});

const server = new WebSocket.Server({ server: httpServer });

server.on('connection', (ws) => {
    console.log("New client connected");

    ws.on('message', (message) => {
        console.log(`Received: ${message}`);

        // 广播收到的消息给所有客户端
        server.clients.forEach(client => {
            if (/*client !== ws && */ client.readyState === WebSocket.OPEN) {
                client.send(message);
                console.log(`222`);
            }
        });
    });

    ws.on('close', () => {
        console.log('Client disconnected');
    });

    // ws.send('welcome to  WebSocket server!');
});